package controllers

import (
	"encoding/json"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"time"
	"yk5_news/cache"
	"yk5_news/models"
)

type NewsController struct {
	beego.Controller
}

func (c *NewsController) Create() {
	var err error

	title := c.GetString("title")
	typeId, _ := c.GetInt("type_id")
	images := c.GetString("images")
	num, _ := c.GetInt("num")
	username := c.GetString("username")
	status := c.GetString("status")

	var news models.News
	news.Title = title
	news.TypeId = typeId
	news.Images = images
	news.Num = num
	news.UserName = username
	news.Status = status

	if err = news.Create(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "新闻添加失败",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code":    500,
		"message": "新闻添加成功",
	}
	c.ServeJSON()
}

func (c *NewsController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")

	var err error
	page, _ := c.GetInt("page")
	pageSize, _ := c.GetInt("pageSize")
	id, _ := c.GetInt("id")

	var news models.News
	var list []models.NewsData

	key := fmt.Sprintf("list_%d_%d_%d", id, page, pageSize)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, key).Result()

	if cacheData == "" {
		list, _ = news.List(id, page, pageSize)
		if len(list) != 0 {
			jsonData, _ := json.Marshal(list)
			cache.Rdb.Set(cache.Ctx, key, jsonData, time.Hour)
		}
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "新闻列表展示失败",
		}
		c.ServeJSON()
		return
	}

	var count int64
	models.DB.Model(&models.News{}).Count(&count)

	c.Data["json"] = map[string]interface{}{
		"code":    200,
		"message": "新闻列表展示成功",
		"data":    list,
		"count":   count,
	}
	c.ServeJSON()
	return
}

func (c *NewsController) Del() {
	var err error

	id, _ := c.GetInt("id")
	var news models.News
	news.ID = uint(id)

	if err = news.GetNewsById(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "系统异常",
		}
		c.ServeJSON()
		return
	}

	if news.Status == "已发布" {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "已发布新闻列表禁止删除",
		}
		c.ServeJSON()
		return
	}

	if err = news.Del(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "新闻删除失败",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code":    200,
		"message": "新闻删除成功",
	}
	c.ServeJSON()
}
